import React from 'react';
import { Menu } from 'antd';
import styles from './index.module.less';
import { useNavigate, useRouteLoaderData, useLocation } from 'react-router-dom';
import useStore from '@/store';
import type { MenuProps } from 'antd';
import { Menu as IMenu } from '@/types';
import { useEffect, useState } from 'react';
import * as Icons from '@ant-design/icons';

const ManagerMenu = () => {
  const [menuList, setMenuList] = useState<MenuItem[] | undefined>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const collapsed = useStore(state => state.collapsed);
  const navigate = useNavigate();
  const { pathname } = useLocation();
  const handleClickLogo = () => {
    navigate('/');
  };
  type MenuItem = Required<MenuProps>['items'][number];
  const data: any = useRouteLoaderData('layout');
  function getItem(
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
    type?: 'group'
  ): MenuItem {
    return {
      label,
      key,
      icon,
      children,
      type
    } as MenuItem;
  }

  const getIcon = (icon?: string) => {
    if (!icon) return <></>;
    const customIcon: { [key: string]: any } = Icons;
    if (!customIcon[icon]) return <></>;
    return React.createElement(customIcon[icon]);
  };

  const getMenuList = (
    menuList: IMenu.MenuItem[],
    treeList: MenuItem[] | undefined = []
  ) => {
    menuList?.forEach((item, index) => {
      if (item.menuType === 1 && item.menuState === 1) {
        if (item.buttons) {
          return treeList.push({
            label: item.menuName,
            key: item.path || index,
            icon: getIcon(item.icon)
          });
        }
        treeList.push(
          getItem(
            item.menuName,
            item.path || index,
            getIcon(item.icon),
            getMenuList(item?.children || [])
          )
        );
      }
    });
    return treeList.length ? treeList : undefined;
  };

  useEffect(() => {
    const treeMenuList = getMenuList(data.menuList);
    setMenuList(treeMenuList);
    setSelectedKeys([pathname]);
  }, []);

  const handleClickMenu = ({ key }: { key: string }) => {
    setSelectedKeys([key]);
    navigate(key);
  };
  return (
    <div className={`${styles['manager-menu']}`}>
      <div
        className={`${styles['logo']} ${collapsed ? '' : styles['isopen']}`}
        onClick={handleClickLogo}
      >
        <img src='http://driver.marsview.cc/imgs/logo.png' alt='' />
        {collapsed ? '' : <span>幕幕货运</span>}
      </div>
      <Menu
        defaultOpenKeys={selectedKeys}
        mode='inline'
        theme='dark'
        items={menuList}
        onClick={handleClickMenu}
        selectedKeys={selectedKeys}
      />
    </div>
  );
};
export default ManagerMenu;
